package com.wdd.atcrowdfunding.controller;

import com.wdd.atcrowdfunding.bean.Advertisement;
import com.wdd.atcrowdfunding.bean.Member;
import com.wdd.atcrowdfunding.bean.Permission;
import com.wdd.atcrowdfunding.bean.User;
import com.wdd.atcrowdfunding.manager.service.AdvertisementService;
import com.wdd.atcrowdfunding.manager.service.UserService;
import com.wdd.atcrowdfunding.potal.service.MemberService;
import com.wdd.atcrowdfunding.util.AjaxResult;
import com.wdd.atcrowdfunding.util.Const;
import com.wdd.atcrowdfunding.util.CpachaUtil;
import com.wdd.atcrowdfunding.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

@Controller
public class DispatcherController {

    @Autowired
    private UserService userService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AdvertisementService advertisementService;



    @RequestMapping("/index")
    public String index(Model model){
        List<Advertisement> advertisementList = advertisementService.selectByStatus(3);
        model.addAttribute("advertisementList",advertisementList);
        return "index";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request,HttpSession session){
//判断是否需要自动登录
        //如果之前登录过，cookie中存放了用户信息，需要获取cookie中的信息，并进行数据库的验证

        boolean needLogin = true;
        String logintype = null ;
        Cookie[] cookies = request.getCookies();
        if(cookies != null){ //如果客户端禁用了Cookie，那么无法获取Cookie信息

            for (Cookie cookie : cookies) {

                if("logincode".equals(cookie.getName())){
                    String logincode = cookie.getValue();
                    System.out.println("获取到Cookie中的键值对"+cookie.getName()+"===== " + logincode);
                    //loginacct=admin&userpwd=21232f297a57a5a743894a0e4a801fc3&logintype=member
                    String[] split = logincode.split("&");
                    if(split.length == 3){
                        String loginacct = split[0].split("=")[1];
                        String userpwd = split[1].split("=")[1];
                        logintype = split[2].split("=")[1];
                        Map<String,Object> paramMap = new HashMap<String,Object>();
                        paramMap.put("loginacct", loginacct);
                        paramMap.put("userpswd", userpwd);
                        paramMap.put("type", logintype);

                        if("user".equals(logintype)){


                            User dbLogin = userService.queryUserLogin(paramMap);

                            if(dbLogin!=null){
                                session.setAttribute(Const.LOGIN_USER, dbLogin);
                                needLogin = false ;
                            }

                            PermissionRoot(session);


                        }else if("member".equals(logintype)){


                            Member dbLogin = memberService.queryMemberLogin(paramMap);

                            if(dbLogin!=null){
                                session.setAttribute(Const.LOGIN_MEMBER, dbLogin);
                                needLogin = false ;
                            }
                        }

                    }
                }
            }
        }

        if(needLogin){
            return "login";
        }else{
            if("user".equals(logintype)){
                return "redirect:/main.htm";
            }else if("member".equals(logintype)){
                return "redirect:/member.htm";
            }
        }
        return "login";
    }

    @RequestMapping("/reg")
    public String reg(){
        return "reg";
    }

    @RequestMapping("/main")
    public String main(){
        return "main";
    }

//    @RequestMapping("/member")
//    public String tomember(){
//        return "member/member";
//    }

    /**
     * 用户登录
     * @param loginacct
     * @param userpswd
     * @param type
     * @param session
     * @return
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public AjaxResult doLogin(String loginacct, String userpswd, String check, String type,String rememberme, HttpServletResponse response,HttpSession session){

        //首先清空session域中的用户或管理员
        session.setAttribute(Const.LOGIN_MEMBER,"");
        session.setAttribute(Const.LOGIN_USER,"");

        AjaxResult ajaxResult = new AjaxResult();
        String checkcode_server = (String) session.getAttribute(Const.CPACHA_TYPE);
        session.removeAttribute(Const.CPACHA_TYPE);//为了保证验证码只能使用一次
        //比较
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //验证码错误
            //注册失败
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("验证码错误");
            return ajaxResult;
        }
        Map<String,Object> paramMap = new HashMap();
        User user = null;
        Member member = null;
        paramMap.put("loginacct",loginacct);
        paramMap.put("userpswd", MD5Util.digest(userpswd));
        if(type.equals("user")){
            user = userService.queryUserLogin(paramMap);
            if(user==null){
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("用户名或密码错误,类型错误");
                return ajaxResult;
            }else{
                session.setAttribute(Const.LOGIN_USER,user);

                //放入cookie
                if("1".equals(rememberme)){
                    String logincode = "\"loginacct="+user.getLoginacct()+"&userpwd="+user.getUserpswd()+"&logintype=user\"";
                    Cookie c = new Cookie("logincode",logincode);
                    c.setMaxAge(60*60*24*14); //2周时间Cookie过期     单位秒
                    c.setPath("/"); //表示任何请求路径都可以访问Cookie
                    response.addCookie(c);
                }


                //---------------------------------------------------------------------
                //查询已拥有的许可，放入session，在界面左侧显示
                PermissionRoot(session);
                //---------------------------------------------------------------------


                ajaxResult.setSuccess(true);
                ajaxResult.setType("user");
                return ajaxResult;
            }
        }
        if(type.equals("member")){
            member = memberService.queryMemberLogin(paramMap);
            if(member==null){
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("用户名或密码错误,类型错误");
                return ajaxResult;
            }else{

                //放入cookie
                if("1".equals(rememberme)){
                    String logincode = "\"loginacct="+member.getLoginacct()+"&userpwd="+member.getUserpswd()+"&logintype=member\"";
                    Cookie c = new Cookie("logincode",logincode);
                    c.setMaxAge(60*60*24*14); //2周时间Cookie过期     单位秒
                    c.setPath("/"); //表示任何请求路径都可以访问Cookie
                    response.addCookie(c);
                }

                session.setAttribute(Const.LOGIN_MEMBER,member);
                ajaxResult.setSuccess(true);
                ajaxResult.setType("member");
                return ajaxResult;
            }
        }

        return ajaxResult;
    }

    /**
     * 用户注销
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        session.invalidate();

        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("logincode")){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    System.out.println("被删除的cookie名字为:"+cookie.getName());
                    response.addCookie(cookie);
                }
            }
        }

        return "redirect:index.htm"; // 防止重复提交
    }

    /**
     * 用户注册
     * @param member
     * @param check
     * @param session
     * @return
     */
    @RequestMapping("/doReg")
    @ResponseBody
    public AjaxResult doReg(Member member, String check,HttpSession session){

        //首先清空session域中的用户或管理员
        session.setAttribute(Const.LOGIN_MEMBER,"");
        session.setAttribute(Const.LOGIN_USER,"");

        AjaxResult ajaxResult = new AjaxResult();
        String checkcode_server = (String) session.getAttribute(Const.CPACHA_TYPE);
        session.removeAttribute(Const.CPACHA_TYPE);//为了保证验证码只能使用一次
        //比较
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //验证码错误
            //注册失败
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("验证码错误");
            return ajaxResult;
        }
        //实名认证状态 0 - 未实名认证， 1 - 实名认证申请中， 2 - 已实名认证 ,设置默认为0
        member.setAuthstatus("0");
        if(memberService.querySelectMemberByLoginacct(member.getLoginacct())){
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("登录名已存在");
            return ajaxResult;
        }
        if(memberService.querySelectMemberByEmail(member.getEmail())){
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("邮箱已注册");
            return ajaxResult;
        }
        member.setUserpswd(MD5Util.digest(member.getUserpswd()));
        memberService.insertMember(member);
        ajaxResult.setSuccess(true);
        ajaxResult.setMessage("注册成功");
        session.setAttribute(Const.LOGIN_MEMBER,member);

        return ajaxResult;
    }

    @RequestMapping("/checkCode")
    public void generateCpacha(HttpServletRequest request, HttpServletResponse response){
        CpachaUtil cpachaUtil = new CpachaUtil();
        String generatorVCode = cpachaUtil.generatorVCode();
        request.getSession().setAttribute(Const.CPACHA_TYPE, generatorVCode);
        BufferedImage generatorRotateVCodeImage = cpachaUtil.generatorRotateVCodeImage(generatorVCode, true);
        try {
            ImageIO.write(generatorRotateVCodeImage, "gif", response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @RequestMapping("/member")
    public String member(){
        return "member/member";
    }


    /**
     * 查询已拥有的许可，放入session，在界面左侧显示
     */
    public void PermissionRoot(HttpSession session){
        //查询已拥有的许可，放入session，在界面左侧显示
        User user = (User) session.getAttribute(Const.LOGIN_USER);
        List<Permission> myPermissions = userService.queryPermissionByUserid(user.getId());
        Permission permissionRoot = null;
        Map<Integer,Permission> map = new HashMap<Integer,Permission>();
        Set<String> myUris = new HashSet<String>(); // 用于拦截器拦截许可权限
        for (Permission innerpermission : myPermissions) {
            map.put(innerpermission.getId(), innerpermission);
            myUris.add("/"+innerpermission.getUrl());
        }
        for (Permission pe : myPermissions) { //100
            //通过子查找父
            //子菜单
            Permission child = pe ; //假设为子菜单
            if(child.getPid() == null ){
                permissionRoot = pe;
            }else{
                //父节点
                Permission parent = map.get(child.getPid());
                parent.getChildren().add(child);
            }
        }
        session.setAttribute("permissionRoot",permissionRoot);
        session.setAttribute(Const.MY_URIS,myUris);
        //end
    }



}
